<script setup lang="ts">
import WrapComponent from '../WrapComponent.vue'
import TableHead from '../TableHead.vue'
import ReportPerson from '../ReportPerson.vue'
import { getFlatternColumns } from '../util'
import type { ReportColumnsItem } from '../../types'

import useInformant from '../useInformant'
import GradeTypeLists from './GradeTypeLists.vue'
import TableTwo from './TableTwo.vue'

import { uuid } from '@/utils'
import { energyMetrologicalReviewApi } from '@/api'

const props = defineProps<{
  dataTime: string
  readonly: boolean
}>()
const title = ref('能源计量器具配备情况统计汇总表')
const columns: ReportColumnsItem[] = [
  { label: '分级、分项', prop: 'gradeType' },
  { label: '级或项的名称', prop: 'gradeName' },
  {
    label: '配备的计量器具类别及数量',
    prop: 'C',
    children: [
      {
        label: '衡器',
        prop: 'CA',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped1' },
          { label: '实配数量（台）', prop: 'realityEquipped1' },
        ],
      },
      {
        label: '电能表',
        prop: 'CB',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped2' },
          { label: '实配数量（台）', prop: 'realityEquipped2' },
        ],
      },
      {
        label: '油流量表（装置）',
        prop: 'CC',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped3' },
          { label: '实配数量（台）', prop: 'realityEquipped3' },
        ],
      },
      {
        label: '气体流量表（装置）',
        prop: 'CD',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped4' },
          { label: '实配数量（台）', prop: 'realityEquipped4' },
        ],
      },
      {
        label: '水流量表（装置）',
        prop: 'CE',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped5' },
          { label: '实配数量（台）', prop: 'realityEquipped5' },
        ],
      },
      {
        label: '温度仪表',
        prop: 'CF',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped6' },
          { label: '实配数量（台）', prop: 'realityEquipped6' },
        ],
      },
      {
        label: '压力仪表',
        prop: 'CG',
        children: [
          { label: '应配数量（台）', prop: 'shouldEquipped7' },
          { label: '实配数量（台）', prop: 'realityEquipped7' },
        ],
      },
    ],
  },
]
const flatternColumns = getFlatternColumns(columns)
const cols = flatternColumns.length - 1

const tempUuid = () => uuid('temp_')

/** 进出用能单位 */
const data1 = ref<[string, ...(string | number)[]][]>([
  [tempUuid(), ...Array(cols).fill('')],
])
/** 进出主要次级用能单位 */
const data2 = ref<[string, ...(string | number)[]][]>(
  Array(2)
    .fill(1)
    .map(() => [tempUuid(), ...Array(cols).fill('')]),
)

/** 主要用能设备 */
const data3 = ref<[string, ...(string | number)[]][]>(
  Array(2)
    .fill(1)
    .map(() => [tempUuid(), ...Array(cols).fill('')]),
)

/** 其他项目 */
const data4 = ref<[string, ...(string | number)[]][]>(
  Array(4)
    .fill(1)
    .map(() => [tempUuid(), ...Array(cols).fill('')]),
)

const summary = ref<{
  uuid: string
  data: (string | number)[]
}>({
      uuid: tempUuid(),
      data: Array(cols - 1).fill(''),
    })

const { informant, setInformant } = useInformant()

const lists1Ref = ref<InstanceType<
  typeof GradeTypeLists
> | null>(null)
const lists2Ref = ref<InstanceType<
  typeof GradeTypeLists
> | null>(null)
const lists3Ref = ref<InstanceType<
  typeof GradeTypeLists
> | null>(null)
const lists4Ref = ref<InstanceType<
  typeof GradeTypeLists
> | null>(null)
const lists5Ref = ref<InstanceType<typeof TableTwo> | null>(
  null,
)

const loading = ref(false)
function filterData(data: any[], type: number): [string, ...(string | number)[]][] {
  // 过滤掉填报人信息
  data = data.filter(v => +v.gradeType === type && v.type !== 2)
  return data.map((v) => {
    return [
      `${v.id}`,
      ...flatternColumns.slice(1).map((vv) => {
        const key = vv.prop
        return v[key]
      }),
    ]
  })
}
async function loadList() {
  loading.value = true
  try {
    const { data }
      = await energyMetrologicalReviewApi.selectToolsAllocate(
        props.dataTime,
      )
    // console.log(data);

    // 更新填报人信息
    const informantData = data.find((v: any) => v.type === 2)
    informantData && setInformant(informantData)

    const d1 = filterData(data, 1)
    d1.length > 0 && (data1.value = d1)

    const d2 = filterData(data, 2)
    d2.length > 0 && (data2.value = d2)

    const d3 = filterData(data, 3)
    d3.length > 0 && (data3.value = d3)

    const d4 = filterData(data, 4)
    d4.length > 0 && (data4.value = d4)
  }
  finally {
    loading.value = false
  }
}

function resolveLists(
  lists: {
    uuid: string
    data: (string | number)[]
  }[],
  gradeType: 1 | 2 | 3 | 4,
) {
  const isTemp = (uuid: string) => uuid.startsWith('temp_')
  const isNotEmpty = (v: {
    uuid: string
    data: (string | number)[]
  }) =>
    !isTemp(v.uuid)
    || v.data.some(
      vv => vv !== '' && vv !== undefined && vv !== null,
    )

  // console.log(
  //   gradeType,
  //   ': ',
  //   toValue(lists).filter(isNotEmpty)
  // );

  const dataTime = toValue(props.dataTime) || (`${new Date().getFullYear()}`)
  return toValue(lists)
    .filter(isNotEmpty)
    .map((v) => {
      const obj = {} as any
      obj.id = Number(v.uuid) || undefined
      obj.gradeType = gradeType
      obj.gradeName = v.data[0] as string
      obj.type = 1
      obj.dataTime = dataTime
      const data = v.data.slice(1)
      data.forEach((vv, ii) => {
        const n = Math.floor((ii + 2) / 2)
        const key
          = ii % 2 === 0
            ? `shouldEquipped${n}`
            : `realityEquipped${n}`
        obj[key] = Number(vv) || undefined
      })
      return obj
    })
}

async function saveStage() {
  const lists1 = lists1Ref.value?.lists
  const lists2 = lists2Ref.value?.lists
  const lists3 = lists3Ref.value?.lists
  const lists4 = lists4Ref.value?.lists

  const list: any[] = [
    ...resolveLists(lists1 || [], 1),
    ...resolveLists(lists2 || [], 2),
    ...resolveLists(lists3 || [], 3),
    ...resolveLists(lists4 || [], 4),
  ]

  // 追加填报人信息
  list.push({
    type: 2,
    dataTime: toValue(props.dataTime) || (`${new Date().getFullYear()}`),
    ...toValue(informant),
  })

  // console.log(list);
  await energyMetrologicalReviewApi.saveOrUpdateToolsAllocate(
    list,
  )
  await lists5Ref.value?.saveStage()
}

onMounted(() => {
  loadList()
})
</script>

<template>
  <WrapComponent>
    <template v-if="$slots.title" #title>
      <slot
        name="title"
        :title="title"
        :save-stage="saveStage"
      />
    </template>
    <div class="width-fill height-fill flex-direction flex">
      <div v-loading="loading">
        <div class="report-table-head">
          <table class="report-table">
            <TableHead
              :columns="columns"
              :show-line-number="false"
            />
          </table>
        </div>
        <table class="report-table" style="height: auto">
          <tbody ref="tbody">
            <GradeTypeLists
              ref="lists1Ref"
              :data="data1"
              :readonly="readonly"
              :grade-type="1"
              grade-type-text="进出用能单位"
            />
            <GradeTypeLists
              ref="lists2Ref"
              :data="data2"
              :readonly="readonly"
              :grade-type="2"
              grade-type-text="进出主要次级用能单位"
              show-summary
            />
            <GradeTypeLists
              ref="lists3Ref"
              :data="data3"
              :readonly="readonly"
              :grade-type="3"
              grade-type-text="主要用能设备"
              show-summary
            />
            <GradeTypeLists
              ref="lists4Ref"
              :data="data4"
              :readonly="readonly"
              :grade-type="4"
              grade-type-text="其他项目"
            />
            <tr>
              <td colspan="2" class="is-calculable">
                <div class="span-cell">
                  合计
                </div>
              </td>
              <td
                v-for="(_s, colIndex) in summary.data"
                :key="colIndex"
                class="is-calculable"
              >
                <div class="span-cell">
                  {{ summary.data[colIndex] }}
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <div class="description-text">
          <p>
            注：其他项目包括：可回收利用余能、能源计量标准、自检自查、能源能量分析等项目。
          </p>
        </div>
      </div>
      <ElDivider />
      <TableTwo
        ref="lists5Ref"
        :readonly="readonly"
        :data-time="dataTime"
        :informant="informant"
      />
      <ReportPerson
        v-model="informant"
        :readonly="readonly"
      />
    </div>
  </WrapComponent>
</template>
